import java.util.PriorityQueue;

public class MaximumSwap {

    public static void main(String[] args) {
        System.out.println(new MaximumSwap().maximumSwap(1993));
    }

    public int maximumSwap1(int num) {
        char[] chars = (num + "").toCharArray();
        PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> {
            if (chars[a] != chars[b]) return chars[b] - chars[a];
            return a - b;
        });
        for (int i = 0; i < chars.length; i++) {
            heap.offer(i);
        }
        int l = -1;
        int r = -1;
        for (int i = 0; i < chars.length; i++) {
            if (i != heap.peek()) {
                l = i;
                int temp = chars[heap.peek()];
                while (!heap.isEmpty() && chars[heap.peek()] == temp) {
                    r = heap.poll();
                }
                break;
            } else heap.poll();
        }
        if (l == -1) return num;
        char temp = chars[l];
        chars[l] = chars[r];
        chars[r] = temp;
        return Integer.parseInt(new String(chars));
    }

    public int maximumSwap(int num) {
        int[] count = new int[10];
        char[] chars = String.valueOf(num).toCharArray();
        int n = chars.length;
        for (int i = 0; i < n; i++) {
            count[chars[i] - '0'] = i;
        }
        for (int i = 0; i < n; i++) {
            for (int j = 9; j > chars[i] - '0'; j--) {
                if (count[j] > i) {
                    char temp = chars[i];
                    chars[i] = chars[count[j]];
                    chars[count[j]] = temp;
                    return Integer.parseInt(new String(chars));
                }
            }
        }
        return num;
    }
}
